package com.steptime.thread.atomic;

import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * 演示原子数组的使用方法
 */
public class AtomicArrayDemo {
    private static  AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(100);

    public static void main(String[] args) {
        Thread[] inCrementThreads = new Thread[100];
        Thread[] deCrementThreads = new Thread[100];
        IncrementArray incrementArray = new IncrementArray(atomicIntegerArray);
        DecrementArray decrementArray = new DecrementArray(atomicIntegerArray);
        for (int i = 0; i < 100; i++) {
            inCrementThreads[i] =new Thread(incrementArray);
            deCrementThreads[i] =new Thread(decrementArray);
            inCrementThreads[i].start();
            deCrementThreads[i].start();
        }
        for (int i = 0; i < 100; i++) {
            try {
                inCrementThreads[i].join();
                deCrementThreads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < atomicIntegerArray.length(); i++) {
            if (atomicIntegerArray.get(i) != 0) {
                System.out.println("出现不为0的值，出错了!");
            }
        }
        System.out.println("验证结束!!!");

    }

    static class IncrementArray implements Runnable{
        AtomicIntegerArray atomicIntegerArray;

        public IncrementArray(AtomicIntegerArray atomicIntegerArray) {
            this.atomicIntegerArray = atomicIntegerArray;
        }

        @Override
        public void run() {
            for (int i = 0; i < atomicIntegerArray.length(); i++) {
                atomicIntegerArray.incrementAndGet(i);
            }

        }
    }

    static class DecrementArray implements Runnable {
        AtomicIntegerArray atomicIntegerArray;

        public DecrementArray(AtomicIntegerArray atomicIntegerArray) {
            this.atomicIntegerArray = atomicIntegerArray;
        }

        @Override
        public void run() {
            for (int i = 0; i < atomicIntegerArray.length(); i++) {
                atomicIntegerArray.decrementAndGet(i);
            }
        }
    }

}
